
package com.bdtop.dbl.ui.activities.device;

import android.app.Activity;
import android.app.Dialog;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Vibrator;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import com.bdtop.dbl.BaseActivity;
import com.bdtop.dbl.DBLApplication;
import com.bdtop.dbl.R;
import com.bdtop.dbl.model.DeviceInfo;
import com.bdtop.dbl.server.ServerApiFactory;
import com.bdtop.dbl.server.response.BaseResponse;
import com.bdtop.dbl.server.response.GetFenceListResponse;
import com.bdtop.dbl.thirdparty.asynchttp.RequestCallback;
import com.bdtop.dbl.ui.adapters.FenceListAdapter;
import com.bdtop.dbl.ui.view.TitleBar;
import com.bdtop.dbl.utils.Constants;
import com.bdtop.dbl.utils.NetworkUtils;
import com.bdtop.dbl.utils.Preferences;

/**
 * @ClassName: FenceActivity
 * @Description: TODO
 * @author: liyongqiang
 * @date:2014-10-10
 */
public class FenceListActivity extends BaseActivity {

    private TitleBar mTitleBar;
    private ListView listview;
    private FenceListAdapter adapter;
    private TextView derviceName;

    String mdn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_fence);
        super.onCreate(savedInstanceState);
        
        mdn = getIntent().getStringExtra(EXTRA_MDN);
        
        initViews();
    }

    public static final String EXTRA_MDN = "extra_mdn";

    public static final void launch(Context context, String mdn) {
        Intent intent = new Intent(context, FenceListActivity.class);
        intent.putExtra(EXTRA_MDN, mdn);
        context.startActivity(intent);
        ((Activity) context).overridePendingTransition(R.anim.slide_in_right,
                R.anim.keep_original_state);
    }

    @Override
    protected void onResume() {
        super.onResume();
        loadData();
    }

    private void loadData() {
        setAndShowWaitingMessage(R.string.loading);
     
        if (TextUtils.isEmpty(mdn)) {
            setAndShowWaitingMessage(R.string.no_device_bind);
            return;
        }
        ServerApiFactory.getApiImpl().getFences(Preferences.getLoginSign(this),
                mdn,
                new RequestCallback() {

                    @Override
                    public void onSuccess(String rawData, Object response) {
                        GetFenceListResponse fenceListResponse = (GetFenceListResponse) response;
                        if (fenceListResponse.getStatus().equals(Constants.REQUEST_SUCCESS)) {
                            adapter.setList(fenceListResponse.getFences());
                            adapter.notifyDataSetChanged();
                        }
                        if (fenceListResponse.getFences() == null
                                || fenceListResponse.getFences().size() < 1) {
                            setAndShowWaitingMessage(R.string.no_fence_bind);
                        } else {
                            clearAndHiddenWaitingMessage();
                        }

                    }

                    @Override
                    public void onError(int statusCode, Throwable e, String rawData) {
                        clearAndHiddenWaitingMessage();
                        if (NetworkUtils.isNetConnect(getApplicationContext())) {
                            showToast(R.string.oper_error);
                        } else {
                            showToast(R.string.net_error);
                        }
                    }
                });
    }

    private void initViews() {

        mTitleBar = (TitleBar) findViewById(R.id.title_bar);
        mTitleBar.setTitle(R.string.fence_manage);
        mTitleBar.setBelongActivity(this);

        derviceName = (TextView) findViewById(R.id.dervice_name);

        String currentDeviceName = "";
        if(DBLApplication.getInstance().deviceInfoList != null){
	        for (DeviceInfo di : DBLApplication.getInstance().deviceInfoList) {
	            if (di.mdn.equals(mdn)) {
	                currentDeviceName = di.name;
	                break;
	            }
	        }
        }

        if (currentDeviceName != null && !TextUtils.isEmpty(currentDeviceName)) {
            derviceName.setText(String.format(getString(R.string.device_name),
                    currentDeviceName));
        }

        Button btn = new Button(this);
        btn.setText(R.string.add);
        btn.setBackgroundResource(R.drawable.selector_title_blue_btn_bg);
        btn.setTextColor(Color.WHITE);
        btn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                if (adapter.getList() != null
                        && adapter.getList().size() >= Constants.MAX_FENCE_COUNT) {
                    showToast(R.string.fence_max_count);
                } else {
                    FenceModiActivity.launch(FenceListActivity.this, null, mdn);
                }
            }
        });
        mTitleBar.addMenu(btn);

        listview = (ListView) findViewById(R.id.listview_fence);
        adapter = new FenceListAdapter(this);
        listview.setAdapter(adapter);
        listview.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int poistion, long itemId) {
                FenceModiActivity.launch(FenceListActivity.this, adapter.getList().get(poistion), mdn);
            }

        });

        listview.setOnItemLongClickListener(new OnItemLongClickListener() {

            @Override
            public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int poistion, long itemId) {
                Vibrator mVibrator = (Vibrator) getApplication().getSystemService(
                        Service.VIBRATOR_SERVICE);
                mVibrator.vibrate(100);
                showDeleteDialog(poistion);
                return true;
            }
        });
    }

    private void showDeleteDialog(final int currIndex) {
        final Dialog dialog = new Dialog(this, R.style.Theme_Light_NoTitle_Dialog);
        View content = LayoutInflater.from(this).inflate(R.layout.dialog_confirm_2, null);

        TextView txMessage = (TextView) content.findViewById(R.id.tx_message);
        txMessage.setText(R.string.deleteTip);

        OnClickListener listener = new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                dialog.dismiss();

                if (arg0.getId() == R.id.btn_confirm) {

                    setAndShowWaitingMessage(R.string.waiting_delete);

                    ServerApiFactory.getApiImpl().fenceDel(
                            Preferences.getLoginSign(FenceListActivity.this),
                            adapter.getList().get(currIndex).getFence_id(),
                            new RequestCallback() {

                                @Override
                                public void onSuccess(String rawData, Object response) {
                                    BaseResponse baseResponse = (BaseResponse) response;
                                    if (baseResponse.getStatus().equals(
                                            Constants.REQUEST_SUCCESS)) {
                                        adapter.getList().remove(currIndex);
                                        adapter.notifyDataSetChanged();
                                    }
                                    showToast(baseResponse.getDesc());
                                    clearAndHiddenWaitingMessage();
                                }

                                @Override
                                public void onError(int statusCode, Throwable e,
                                        String rawData) {
                                    if (NetworkUtils.isNetConnect(getApplicationContext())) {
                                        showToast(R.string.oper_error);
                                    } else {
                                        showToast(R.string.net_error);
                                    }
                                    clearAndHiddenWaitingMessage();
                                }
                            });
                }
            }
        };

        content.findViewById(R.id.btn_confirm).setOnClickListener(listener);
        content.findViewById(R.id.btn_cancel).setOnClickListener(listener);

        dialog.setCancelable(true);
        dialog.setCanceledOnTouchOutside(true);
        dialog.setContentView(content);
        dialog.show();
    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(R.anim.keep_original_state,
                R.anim.slide_out_right);
    }
}
